package redis

import (
	"biliClient/global"
	"context"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
)

var (
	client *redis.Client
	ctx =context.Background()
)

// init redis初始化
func init() {
	c := global.Config.Redis
	client = redis.NewClient(&redis.Options{
		Addr:         c.Address,
		Password:     c.Password, // no password set
		DB:           c.DB,       // use default DB
		PoolSize:     100,
		MinIdleConns: 10,
		DialTimeout:  5 * time.Second,
		ReadTimeout:  1 * time.Second,
		WriteTimeout: 1 * time.Second,
		PoolTimeout:  2 * time.Second,
	})
	pong, err := client.Ping(ctx).Result()
	if err != nil {
		fmt.Println("初始化失败")
	} else {
		fmt.Println("redis connect ping response:", pong)
	}
}

func SetValue(key string, value int, timeOut int) {
	key = fmt.Sprintf("client-%v",key)
	client.Set(ctx,key, value, time.Second*time.Duration(timeOut))
}

//GetLis 获取list任务列表
func GetLis(key string) []string {
	key = fmt.Sprintf("list-client-%v", key)
	if client.Exists(ctx,key).Val() == 1 {
		result, err := client.LRange(ctx,key, 0, -1).Result()
		if err != nil{
			return nil
		}
		client.Del(ctx,key).Val()
		return result
	}
	return nil
}
